import datetime

from django.shortcuts import render

# Create your views here.
from rest_framework import mixins
from rest_framework import status

from rest_framework.filters import OrderingFilter

from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from question.models import Troubles,NavigationLabel, Respond, RespondComment, TroublesLike
from question.serializers import TroublesListSerializer, NavigationLabelSerializer, TroublesDetailSerializer, \
    RespondSerializer, CommentSerializer, SubmitQuestionSerializer


class TroublesView(ListAPIView):
    serializer_class = TroublesListSerializer

    """问题列表"""

    def get_queryset(self):
        label_id = self.kwargs['label_id']

        if label_id == '0':

            if self.request.query_params['ordering'] == 'not_answer':

                return Troubles.objects.filter(is_delete=0, answer_count=0).order_by('-create_time')

            elif self.request.query_params['ordering'] == "news_respond":

                return Troubles.objects.filter(is_delete=0).order_by('-new_answer_time')

            else:
                return Troubles.objects.filter(is_delete=0).order_by('-answer_count')

        else:
            if self.request.query_params['ordering'] == 'not_answer':

                return Troubles.objects.filter(is_delete=0, answer_count=0, troubleslabel__navigation_label_id=label_id).order_by('-create_time')

            elif self.request.query_params['ordering'] == "news_respond":
                return Troubles.objects.filter(is_delete=0, troubleslabel__navigation_label_id=label_id).order_by('-new_answer_time')

            else:
                return Troubles.objects.filter(is_delete=0, troubleslabel__navigation_label_id=label_id).order_by('-answer_count')



class NavigationLabelView(ListAPIView):

    """导航标签视图"""
    pagination_class = None
    serializer_class = NavigationLabelSerializer

    queryset = NavigationLabel.objects.all()[0:4]



class HotLabelView(ListAPIView):

    """热门导航标签"""
    pagination_class = None
    serializer_class = NavigationLabelSerializer

    queryset = NavigationLabel.objects.all().order_by('-fans')


class TroublesDetailView(RetrieveAPIView):
    serializer_class = TroublesDetailSerializer
    """问题详情页"""
    def get_queryset(self):
        pk = self.kwargs['pk']
        return Troubles.objects.filter(pk=pk)




class RespondViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,GenericViewSet):

    """回答列表"""
    pagination_class = None
    serializer_class = RespondSerializer
    # permission_classes = [IsAuthenticated]


    def get_queryset(self):

        pk = self.kwargs["pk"]
        return Respond.objects.filter(question_id=pk)

    # def get_permissions(self):
    #     """根据请求方法设置权限"""
    #     if self.request.method == 'GET':
    #         return []
    #     return super(RespondViewSet, self).get_permissions()


    def create(self, request, *args, **kwargs):

        pk = self.kwargs['pk']
        user = request.user
        print('%s---' % user)

        time_now = datetime.datetime.now()

        troubles = Troubles.objects.get(pk=pk)
        troubles.new_answer_name = user.username
        troubles.nwe_answer_time = time_now
        troubles.save()

        return super().create(request, *args, **kwargs)


class CommentView(CreateAPIView):
    """评论列表"""
    pagination_class = None
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated, ]

    def get_queryset(self):
        pk = self.kwargs['pk']

        return RespondComment.objects.filter(respond_id=pk)


class TroublesLikeView(APIView):
    """顶踩实现"""
    permission_classes = [IsAuthenticated, ]

    def post(self, request):
        question_id = request.data['question_id']
        like_state = request.data['like_state']

        question_id = int(question_id)
        user = request.user

        query = TroublesLike.objects.filter(user=user, question_id=question_id, is_delete=0)

        if query:
            return Response({'message': '请取消点赞,才能再点'}, status=status.HTTP_400_BAD_REQUEST)

        else:


            question = Troubles.objects.get(id=question_id)

            if like_state == 1:
                question.like_count += 1
                question.save()
                query_new = TroublesLike.objects.create(user=user,
                                                        like_state=like_state, question_id=question_id)
                query_new.save()

            elif like_state == 2:
                question.like_count -= 1
                question.save()
                query_new = TroublesLike.objects.create(user=user,
                                                        like_state=like_state, question_id=question_id)
                query_new.save()

        return Response({'message': 'ok'})


class TroublesCancelLikeView(APIView):
    """取消顶踩"""
    permission_classes = [IsAuthenticated, ]

    def post(self, request):

        user = request.user
        question_id = request.data['question_id']
        question_id = int(question_id)

        try:
            query = TroublesLike.objects.filter(user=user, question_id=question_id, is_delete=0).get()
            question = Troubles.objects.get(id=question_id)
        except Exception:
            return Response({'message': '请点赞,在取消'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            if query.like_state == 1:

                question.like_count -= 1
                query.is_delete = 1



            elif query.like_state == 2:

                question.like_count += 1
                query.is_delete = 1

            question.save()
            query.save()
            return Response({'message': '取消成功'})


# class LabelLikeView(ListAPIView):
#     pagination_class = None
#     serializer_class = NavigationLabelSerializer
#
#     queryset = NavigationLabel.objects.all()
#
#
# class SubmitQuestionView(CreateAPIView):
#
#     queryset = Troubles.objects.all()
#
#     serializer_class = SubmitQuestionSerializer
#
#
#     def create(self, request, *args, **kwargs):





